import SpaceBot from '@/components/SpaceBot';
import { sllm_articles, sllm_domains } from '@/services/ant-design-pro/departmentSpace.ts';
import { connect } from '@umijs/max';
import { message, Modal, Pagination } from 'antd';
import { nanoid } from 'nanoid';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
const dayjs = require('dayjs');
const DepartmentSpace: React.FC = (props: any) => {
  const [expendBot, setExpendBot] = useState(false); //收起展开
  const [totalCount, setTotalCount] = useState(0); // 文章总数
  const [domainList, setDomainList] = useState([]); //领域列表
  const [domainActive, setDomainActive] = useState(0); //领域选中
  const [articleList, setArticleList] = useState([]); //文章列表
  const [detailOpen, setDetailOpen] = useState(false); //详情弹窗
  const [curArticle, setCurArticle] = useState({
    domain: [],
    title: '',
    main_body: '',
    updated_at: 1700538984000,
  }); //当前弹窗文章
  const [pageOption, setPageOption] = useState({ page: 1, per_page: 10 }); //分页默认值
  const articleEleRef = useRef<any>(null); //弹窗文档的外部容器 用于回滚滚动条
  const articleElement = useRef<any>(null);
  const hitClick = (data: any) => {
    console.log('点击命中', data);
  };
  //格式化 训练时间
  const formatAtTime = (timestamp: any) => {
    return dayjs(timestamp).format('YYYY/MM/DD');
  };
  //领域标签切换
  const toggleActive = (index: number) => {
    setDomainActive(index);
    setPageOption({
      page: 1,
      per_page: 10,
    });
  };

  //页码change
  const paginationChange = (params: any) => {
    setPageOption({
      ...pageOption,
      page: params,
    });
  };

  //打开弹窗
  const openModal = (data: any) => {
    setDetailOpen(true);
    setCurArticle(data);
    //将\n替换成p标签包裹文字
    const mainBody = data?.main_body
      .split('\n')
      .map((paragraph: any) => `<p>${paragraph}</p>`)
      .join('');
    articleElement.current = React.createElement('div', {
      dangerouslySetInnerHTML: { __html: mainBody },
    });
    //打开弹窗时 回滚滚动条到顶部
    setTimeout(() => {
      if (articleEleRef.current) {
        articleEleRef.current.scrollTop = 0;
      }
    }, 200);
  };

  //查询全部领域
  const getsllmDomains = async () => {
    let res = await sllm_domains({});
    if (res.code === 0) {
      setDomainList(res.data);
    } else {
      message.error(res.msg);
    }
  };
  //获取部门知识数据列表
  const getsllmArticles = async () => {
    let data: any = {
      ...pageOption,
    };
    if (domainList.length > 0) {
      data.domain_id = domainList[domainActive]?.id;
    }
    let res = await sllm_articles(data);
    if (res.code === 0) {
      setTotalCount(res.data.total_count || 0);
      setArticleList(res.data.data || []);
    } else {
      message.error(res.msg);
    }
  };

  //获取领域分类列表
  useEffect(() => {
    props.dispatch({
      type: 'spaceBot/updateStateAsync',
      payload: {
        curTab: 'department',
      },
    });
    getsllmDomains();
  }, []);
  //获取文章列表
  useEffect(() => {
    getsllmArticles();
  }, [pageOption]);

  return (
    <div className="departmentSpaceWrap">
      <div className={`depaSpaceLeft ${expendBot ? '' : 'marginRight'}`}>
        <div className="depaSpaceTitle">部门知识空间</div>
        <div className="depaSpaceTab">
          {domainList &&
            domainList.length > 0 &&
            domainList.map((item: any, index: number) => {
              return (
                <div
                  key={item.id}
                  className={`depaSpaceTabList ${domainActive === index ? 'active' : ''}`}
                  onClick={() => toggleActive(index)}
                >
                  {item.name} {item.count}
                </div>
              );
            })}
        </div>
        <div className="depaSpaceContent">
          {articleList &&
            articleList.length > 0 &&
            articleList.map((item: any) => {
              return (
                <div key={item.id} className="depaSpaceList" onClick={() => openModal(item)}>
                  <div className="depaSpaceTagBox">
                    {item.domain &&
                      item.domain.length > 0 &&
                      item.domain.map((item2: any) => {
                        return (
                          <div key={item2.id} className="depaSpaceTag">
                            {item2.name}
                          </div>
                        );
                      })}
                  </div>
                  <div className="depaSpaceTit">{item.title}</div>
                  <div className="depaSpaceCont">{item.main_body}</div>
                  <div className="depaSpaceQuote">
                    {/* 引用<span className="depaSpaceQuoteNum">123</span>次 */}
                    <span className="depaSpaceQuoteNum">{item.source}</span>
                  </div>
                  <div className="depaSpaceTime">
                    {item.released_at && <>发布于 {formatAtTime(item.released_at)}</>}
                  </div>
                </div>
              );
            })}
        </div>
        <div className="depaSpacePagination">
          <Pagination
            current={pageOption.page}
            defaultCurrent={1}
            pageSize={pageOption.per_page}
            total={totalCount}
            showSizeChanger={false}
            onChange={paginationChange}
          />
        </div>
      </div>
      <div className="depaSpaceRight">
        {/* <SpaceBot router="spaceHome" setExpendBot={setExpendBot} hitClick={hitClick}></SpaceBot> */}
        <SpaceBot router="spaceData" setExpendBot={setExpendBot} hitClick={hitClick}></SpaceBot>
      </div>
      <Modal
        centered
        className="departmentDetailModal"
        title={[
          <div className="" key={nanoid()}>
            <div className="departmentDetailTitleBox">
              {curArticle?.domain &&
                curArticle?.domain?.length > 0 &&
                curArticle?.domain?.map((item2: any) => {
                  return (
                    <div key={item2.id} className="departmentDetailTag">
                      {item2.name}
                    </div>
                  );
                })}
              <div className="departmentDetailTitle">{curArticle?.title}</div>
            </div>
          </div>,
        ]}
        open={detailOpen}
        onCancel={(e) => {
          e.stopPropagation();
          setDetailOpen(false);
        }}
        width={650}
        footer={[
          <div className="departmentDetailFooterBox" key={nanoid()}>
            {curArticle?.released_at && (
              <span className="departmentDetailFooterInfo">
                发布于 {formatAtTime(curArticle?.released_at)}
              </span>
            )}
            <span className="departmentDetailFooterInfo2" style={{ color: '#397bff' }}>
              {curArticle?.source}
            </span>
            {/* <span className='departmentDetailFooterInfo'>引用 202 次</span> */}
          </div>,
        ]}
      >
        <div className="articleEleRef" ref={articleEleRef}>
          {articleElement.current}
        </div>
      </Modal>
    </div>
  );
};
// export default DepartmentSpace;
export default connect(({ spaceBot }) => ({ spaceBot }))(DepartmentSpace);
